package com.iplay.service.hotel.discount;

import java.text.ParseException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.iplay.component.date.FeastBookingDateFormatter;
import com.iplay.dao.hotel.HotelDAO;
import com.iplay.dao.hotel.discount.HotelDiscountDAO;
import com.iplay.entity.hotel.discount.HotelDiscountDO;

@Component
public class HotelDiscountAsyncTask {

	@Autowired
	private FeastBookingDateFormatter formatter;

	@Autowired
	private HotelDiscountDAO hotelDiscountDAO;
	
	@Autowired
	private HotelDAO hotelDAO;

	@Async
	public void saveHotelDiscount(int hotelId, List<HotelDiscount> discounts) {
		if(hotelDAO.findOne(hotelId) == null)
			return;
		discounts.forEach(d -> {
			Long date = -1L;
			try {
				date = formatter.parseToDateWithDefaultDateFormat(d.getDate()).getTime();
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (date != -1) {
				HotelDiscountDO hotelDiscountDO = hotelDiscountDAO.findByHotelIdAndDate(hotelId, date);
				if(hotelDiscountDO == null){
					hotelDiscountDO = new HotelDiscountDO(hotelId, date, d.getDiscount());
				}else{
					hotelDiscountDO.setDiscount(d.getDiscount());
				}
				hotelDiscountDAO.save(hotelDiscountDO);
			}
		});
	}
}
